import { View, ScrollView } from "@tarojs/components";
import Taro, { useDidShow } from "@tarojs/taro";
import "./index.less";
import { OutlineInput, ImageCard, Tabs, SideNav, Empty } from "@/components";
import {
  SearchIcon,
  PlusIcon,
  DumbbellIcon,
  Barbell,
  KettlebellIcon,
} from "@/components/Icons";
import { useState, useEffect } from "react";
import { getMotions } from "@/request";
import { TMotion } from "@/types";
import { deepClone, GroupOptions, CategoryOptions } from "@/utils";
import useMotionFilter from "@/hooks/useMotionFilter";

type Props = {
  mode?: "base" | "check";
  onClickMotion?: (data: TMotion) => void;
  checked?: TMotion[];
};
export default function MotionList({
  mode = "base",
  onClickMotion,
  checked = [],
}: Props) {
  const [motions, setMotions] = useState<Array<TMotion>>([]);
  useEffect(() => {
    // 用于组件初始化
    if (mode === "check") {
      handleGetMotion();
    }
    Taro.eventCenter.on("refresh", handleGetMotion);
    return () => {
      Taro.eventCenter.off("refresh", handleGetMotion);
    };
  }, []);

  // 用于页面初始化
  useDidShow(() => {
    handleGetMotion();
  });

  const handleGetMotion = async () => {
    const data = await getMotions();
    setMotions(data);
  };

  // 过滤
  const {
    group,
    category,
    keyword,
    handleChangeKeyword,
    handleChangeCategory,
    handleChangeGroup,
    filterFun,
  } = useMotionFilter();
  const filteredMotions = motions.filter(filterFun);

  const handleAddMotion = () => {
    Taro.navigateTo({
      url: `/pages/motion-add/index`,
    });
  };

  let afterGroupOptions = deepClone(GroupOptions);

  if (mode === "check") {
    for (const item of checked) {
      const group = afterGroupOptions.find((opt) => opt.value === item.group);
      if (group) {
        group.sub = (group.sub || 0) + 1;
      }
    }
  }

  const getTool = (tool: number, size = 1.2) => {
    switch (tool) {
      case 1:
        return <DumbbellIcon type="primary" size={size} />;
      case 2:
        return <KettlebellIcon type="primary" size={size} />;
      case 3:
        return <Barbell type="primary" size={size} />;
      default:
        return null;
    }
  };

  return (
    <>
      <View className="motion-list">
        <View className="motion-list-header">
          <View className="search-bar">
            <OutlineInput
              icon={<SearchIcon type="default" />}
              value={keyword}
              onValueChange={handleChangeKeyword}
            />
            <View onClick={handleAddMotion}>
              <PlusIcon type="primary" />
            </View>
          </View>
          <Tabs
            options={CategoryOptions}
            value={category}
            onChange={handleChangeCategory}
            style={{ marginTop: Taro.pxTransform(16) }}
          />
        </View>

        <View style={{ display: "flex" }}>
          <SideNav
            options={afterGroupOptions}
            value={group}
            onChange={(v) => {
              handleChangeGroup(v);
            }}
            disabled={category === 1}
          />

          <ScrollView
            scrollY
            style={{
              height:
                mode === "base" ? "calc(100vh - 100px)" : "calc(100vh - 164px)",
            }}
          >
            {filteredMotions.length !== 0 ? (
              <View className="content">
                {filteredMotions.map((item) => (
                  <ImageCard
                    mode={mode}
                    key={item._id}
                    img={item.img}
                    title={item.name}
                    canHandle={item.canHandle}
                    tool={item.tool}
                    className={
                      mode === "check" &&
                      checked.find((motion) => motion._id === item._id)
                        ? "active"
                        : ""
                    }
                    detailAction={item._id}
                    onCheck={() => onClickMotion && onClickMotion(item)}
                    showHelp={mode === "check"}
                  />
                ))}
              </View>
            ) : (
              <View className="content-empty">
                <Empty text="检索不到相关动作" />
              </View>
            )}
          </ScrollView>
        </View>
      </View>
    </>
  );
}
